const crypto = require("crypto"),
http = require("http"),
url = require("url"),
log = require("./log"),
app_secret = '9bb708f72f48d4728977a4b47ad90cd5';

var date = new Date(),
sDate = date.getFullYear();
sDate += '-'
sDate += (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1) + '-'
sDate += (date.getDate() < 10 ? '0' : '') + date.getDate() + ' '
sDate += (date.getHours() < 10 ? '0' : '') + date.getHours() + ':'
sDate += (date.getMinutes() < 10 ? '0' : '') + date.getMinutes() + ':'
sDate += (date.getSeconds() < 10 ? '0' : '') + date.getSeconds()
var reqObj = {
	timestamp : sDate,
	v : '2.0',
	app_key : '23449940',
	partner_id : 'top-apitools',
	session : '6100010c4d584a656110f422c29983490ecc9eaebc3811265717161',
	format : 'json',
	sign_method : 'md5',
	fields : 'num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick',
	method : 'taobao.tbk.item.info.get',
	num_iids : '44905182621'
},
keyList = []
for (key in reqObj) {
	keyList.push(key)
}
var data = app_secret;
keyList.sort().forEach(key => {
	data += key + reqObj[key]
})
data += app_secret
reqObj.sign = crypto.createHash("md5").update(data).digest("hex").toUpperCase();
var sUrl = 'http://gw.api.taobao.com/router/rest?';
for (key in reqObj) {
	sUrl += key + '=' + reqObj[key] + '&'
}

var urlObj = url.parse(sUrl, true),
options = {
	host : urlObj.hostname,
	port : urlObj.port,
	path : urlObj.pathname,
	method : 'GET'
}
if (urlObj.search)
	options.path += urlObj.search.replace(/ /g, '+');
const req = http.request(options, (res) => {
		var body = []
		res.on('data', (chunk) => {
			body.push(chunk)
		}).on('end', () => {
			var resObj = JSON.parse(Buffer.concat(body).toString());
			log(Buffer.concat(body).toString())
		}).on('error', (err) => {
			log(err)
		})
	});
req.on('error', (err) => {
	log(err)
});
req.end()

/*getHtml("http://s.click.taobao.com/aKhwZTx", (url, html) => {
bol('http://s.click.taobao.com/t_js?tu=http%3A%2F%2Fs.click.taobao.com%2Ft%3Fe%3Dm%253D2%2526s%253Dl9zniN7T0HMcQipKwQzePOeEDrYVVa64LKpWJ%252Bin0XLjf2vlNIV67kS%252B9KKLuBKLWI6w0dMGH8jpsnD0TxWZdulHOGiVatmGoQ9qCDbcc2vcShItn7fdxRsn5Vggn5eKQkfzUIfpopuxK1bSh%252BcYHQ%252FwFtdb3lRFxg5p7bh%252BFbQ%253D%26pvid%3D10_223.73.224.206_53856_1473346633705%26ref%3D%26et%3DO%252B1rhCcx%252FwN375YtSpmrA0fiHnYt4bQH')
getHtml('http://s.click.taobao.com/t?e=m%3D2%26s%3Dl9zniN7T0HMcQipKwQzePOeEDrYVVa64LKpWJ%2Bin0XLjf2vlNIV67kS%2B9KKLuBKLWI6w0dMGH8jpsnD0TxWZdulHOGiVatmGoQ9qCDbcc2vcShItn7fdxRsn5Vggn5eKQkfzUIfpopuxK1bSh%2BcYHQ%2FwFtdb3lRFxg5p7bh%2BFbQ%3D&pvid=10_223.73.224.206_53856_1473346633705&ref=&et=ScKpYpEs7Jh2TBDcpT4PEEt7%2BsYsjG9d', (url, html) => {
log(url)
log(html)
})
})*/

function getHtml(sUrl, resolve) {
	var urlObj = url.parse(sUrl, true),
	options = {
		host : urlObj.hostname,
		port : urlObj.port,
		path : urlObj.pathname,
		method : 'GET',
		headers : {
			'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36'
		}
	}
	if (urlObj.search)
		options.path += urlObj.search.replace(/ /g, '+');
	const req = http.request(options, (res) => {
			var body = []
			res.on('data', (chunk) => {
				body.push(chunk)
			}).on('end', () => {
				if (res.headers.location) {
					getHtml(res.headers.location, resolve)
				} else {
					log(res.statusCode)
					resolve(sUrl, Buffer.concat(body).toString())
				}
			}).on('error', (err) => {
				log(err)
			})
		});
	req.on('error', (err) => {
		log(err)
	})
	req.end()
}

function htmlspecialchars(str) {
	str = str.replace(/</g, '&lt;');
	str = str.replace(/>/g, '&gt;');
	str = str.replace(/"/g, '&quot;');
	str = str.replace(/'/g, '&#039;');
	return str;
}

function bol(sUrl) {
	location = url.parse(sUrl)
		var schema = (("https:" == location.protocol) ? "https" : "http");
	var qs = location.search.split("?")[location.search.split("?").length - 1].split("&");
	qso = {};
	for (var i = 0; i < qs.length; i++) {
		if (qs[i] != "") {
			var tmpa = qs[i].split("=");
			qso[tmpa[0]] = tmpa[1] ? tmpa[1] : "";
		}
	}

	if (!qso.tu) {
		exit;
	}

	var jump_url;
	if (qso.tu.indexOf("https") === 0) {
		jump_url = qso.tu.substr(5);
	} else if (qso.tu.indexOf("http") === 0) {
		jump_url = qso.tu.substr(4);
	} else {
		exit;
	}

	var jump_address = schema + jump_url;

	var real_jump_address = unescape(jump_address);
	if (htmlspecialchars(real_jump_address).length != real_jump_address.length) {
		exit;
	}

	if (jump_url.indexOf("%3A%2F%2Fs.click.taobao.com%2F") === 0
		 || jump_url.indexOf("%3A%2F%2Fi.click.taobao.com%2F") === 0
		 || jump_url.indexOf("%3A%2F%2Fglobal.click.taobao.com%2F") === 0
		 || jump_url.indexOf("%3A%2F%2Fs.click.alimama.com%2F") === 0
		 || jump_url.indexOf("%3A%2F%2Fitem8.taobao.com%2F") === 0
		 || jump_url.indexOf("%3A%2F%2Fshop8.taobao.com%2F") === 0) {
		getHtml(real_jump_address, (url, html) => {
			log(url)
			log(html)
		})
	}
}
